package com.android.mios.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.android.mios.R;
import com.android.mios.intenet.PollLoop;
import com.android.mios.intenet.WebData;
import com.android.mios.model.Device;
import com.android.mios.util.TLog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class CurtainGridViewAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private List<Device> mList;
	private int resource;

	private int[] CURTAIN_DEGREE = { R.drawable.curtain_close,
			R.drawable.curtain_2, R.drawable.curtain_3, R.drawable.curtain_4,
			R.drawable.curtain_5, R.drawable.curtain_open };
	private Context mContext;
	private final static int TYPE_OPEN = 1;
	private final static int TYPE_STOP = 2;
	private final static int TYPE_CLOSE = 3;
	private final static int TYPE_SCROLL = 4;
	private final ConcurrentHashMap<Integer, List<CurtainAsyncTask>> mCache;
	private final ConcurrentHashMap<Integer, Boolean> mRunMap;

	private static final int MIN_PROGRESS = 10;

	public CurtainGridViewAdapter(Context context, List<Device> data,
			int resource) {

		mInflater = LayoutInflater.from(context);
		mList = data;
		this.resource = resource;
		mContext = context;
		mCache = new ConcurrentHashMap<Integer, List<CurtainAsyncTask>>();
		mRunMap = new ConcurrentHashMap<Integer, Boolean>();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {
		// TODO Auto-generated method stub

		final Device device = mList.get(position);

		if (convertView == null)
			convertView = mInflater.inflate(resource, null);

		final ImageView img_curtain = (ImageView) convertView
				.findViewById(R.id.image_curtain);

		final SeekBar seekBar = (SeekBar) convertView
				.findViewById(R.id.seekbar_curtain_up_down);

		final ProgressBar progress = (ProgressBar) convertView
				.findViewById(R.id.progress_curtain_loading);
		progress.setTag(device.id);

		final RadioButton btn_open = (RadioButton) convertView
				.findViewById(R.id.radio_curtain_open);
		final RadioButton btn_stop = (RadioButton) convertView
				.findViewById(R.id.radio_curtain_stop);
		final RadioButton btn_close = (RadioButton) convertView
				.findViewById(R.id.radio_curtain_close);

		TextView textName = (TextView) convertView
				.findViewById(R.id.txt_curtain_name);
		textName.setText(device.toString());

		Boolean isRuning = mRunMap.get(device.id);
		List<CurtainAsyncTask> taskList = mCache.get(device.id);

		if ((isRuning == null || !isRuning)
				&& (taskList == null || taskList.isEmpty()))
			progress.setVisibility(View.GONE);
		else
			progress.setVisibility(View.VISIBLE);

		int level = 0;
		if (device.settings.containsKey("level"))
			level = Integer.parseInt(device.settings.get("level"));

		if (level == 0) {
			// btn_close.setOnCheckedChangeListener(null);
			btn_close.setChecked(true);
			img_curtain.setBackgroundResource(CURTAIN_DEGREE[0]);
		} else if (level == 100) {

			// btn_open.setOnCheckedChangeListener(null);
			btn_open.setChecked(true);
			img_curtain
					.setBackgroundResource(CURTAIN_DEGREE[CURTAIN_DEGREE.length - 1]);

		} else {

			// btn_stop.setOnCheckedChangeListener(null);
			btn_stop.setChecked(true);
			img_curtain
					.setBackgroundResource(CURTAIN_DEGREE[(level - 1) / 20 + 1]);
		}
		seekBar.setOnSeekBarChangeListener(null);
		seekBar.setProgress(level);
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_SCROLL,device.serialNumber);
				addTask(mLightAsyncTask, device.id);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				if (progress == 0) {
					// btn_close.setOnCheckedChangeListener(null);
					btn_close.setChecked(true);
					img_curtain.setBackgroundResource(CURTAIN_DEGREE[0]);
				} else if (progress == 100) {

					// btn_open.setOnCheckedChangeListener(null);
					btn_open.setChecked(true);
					img_curtain
							.setBackgroundResource(CURTAIN_DEGREE[CURTAIN_DEGREE.length - 1]);

				} else {

					// btn_stop.setOnCheckedChangeListener(null);
					btn_stop.setChecked(true);
					img_curtain
							.setBackgroundResource(CURTAIN_DEGREE[(progress - 1) / 20 + 1]);
				}
			}
		});

		btn_open.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_OPEN,device.serialNumber);
				addTask(mLightAsyncTask, device.id);
			}
		});

		btn_stop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_STOP,device.serialNumber);
				addTask(mLightAsyncTask, device.id);

			}
		});

		btn_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				img_curtain.setBackgroundResource(CURTAIN_DEGREE[0]);
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_CLOSE,device.serialNumber);
				addTask(mLightAsyncTask, device.id);

			}
		});

		ImageButton btn_minus = (ImageButton) convertView
				.findViewById(R.id.btn_curtain_minus);
		btn_minus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int iProgress = seekBar.getProgress();
				iProgress = iProgress - MIN_PROGRESS;
				iProgress = iProgress >= 0 ? iProgress : 0;
				seekBar.setProgress(iProgress);
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_SCROLL,device.serialNumber);
				addTask(mLightAsyncTask, device.id);

			}
		});
		
		ImageButton btn_plus = (ImageButton) convertView
				.findViewById(R.id.btn_curtain_plus);
		btn_plus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int iProgress = seekBar.getProgress();
				iProgress = iProgress + MIN_PROGRESS;
				iProgress = iProgress >= 100 ? 100 : iProgress;
				seekBar.setProgress(iProgress);
				CurtainAsyncTask mLightAsyncTask = new CurtainAsyncTask(
						progress, device.id, parent, seekBar.getProgress(),
						TYPE_SCROLL,device.serialNumber);
				addTask(mLightAsyncTask, device.id);
			}
		});
		
		return convertView;
	}

	class CurtainAsyncTask extends AsyncTask<Void, Void, String> {

		ProgressBar progress;
		int id;
		ViewGroup parent;
		int iProgress;
		int type;
		int serialNumber;

		private CurtainAsyncTask(ProgressBar progress, int id,
				ViewGroup parent, int iProgress, int type,int serialNumber) {
			this.progress = progress;
			this.id = id;
			this.parent = parent;
			this.iProgress = iProgress;
			this.type = type;
			this.serialNumber=serialNumber;
		}

		@Override
		protected void onPreExecute() {

			if (progress.getVisibility() != View.VISIBLE)
				progress.setVisibility(View.VISIBLE);
			mRunMap.put(id, true);

		}

		protected String doInBackground(Void... params) {

			if (type == TYPE_OPEN)
				return WebData.getInstance().sendServiceActionWithResponse(
						PollLoop.getInstance().getEngineForSerialNumber(serialNumber), "lu_action",
						"urn:upnp-org:serviceId:Dimming1",
						"SetLoadLevelTarget",
						"DeviceNum=" + id + "&newLoadlevelTarget=" + 100);
			else if (type == TYPE_STOP)
				return WebData.getInstance().sendServiceActionWithResponse(
						PollLoop.getInstance().getEngineForSerialNumber(serialNumber), "lu_action",
						"urn:upnp-org:serviceId:WindowCovering1", "Stop",
						"DeviceNum=" + id);
			else if (type == TYPE_CLOSE)
				return WebData.getInstance().sendServiceActionWithResponse(
						PollLoop.getInstance().getEngineForSerialNumber(serialNumber), "lu_action",
						"urn:upnp-org:serviceId:Dimming1",
						"SetLoadLevelTarget",
						"DeviceNum=" + id + "&newLoadlevelTarget=" + 0);
			else if (type == TYPE_SCROLL)
				return WebData.getInstance().sendServiceActionWithResponse(
						PollLoop.getInstance().getEngineForSerialNumber(serialNumber), "lu_action",
						"urn:upnp-org:serviceId:Dimming1",
						"SetLoadLevelTarget",
						"DeviceNum=" + id + "&newLoadlevelTarget=" + iProgress);
			return "";

		}

		@Override
		protected void onPostExecute(String result) {

			if (result.equals("")) {
				Toast.makeText(mContext, R.string.operation_fails,
						Toast.LENGTH_SHORT).show();
				//((DeviceBaseActivity) mContext).setiNeedUpdateCount(-1);
				notifyDataSetChanged();
			} else if (result.startsWith("ERROR")) {
				Toast.makeText(mContext, result.substring(6),
						Toast.LENGTH_SHORT).show();
				//((DeviceBaseActivity) mContext).setiNeedUpdateCount(-1);
				notifyDataSetChanged();
			}

			mRunMap.put(id, false);

			List<CurtainAsyncTask> taskList = mCache.get(id);
			if (taskList != null && !taskList.isEmpty()) {

				CurtainAsyncTask mLightAsyncTask = taskList.get(0);

				taskList.remove(0);

				mLightAsyncTask.execute();

			} else {
				ProgressBar progress = (ProgressBar) parent.findViewWithTag(id);
				if (progress != null)
					progress.setVisibility(View.GONE);

			}

		}
	};

	private void addTask(CurtainAsyncTask task, int id) {

		//((DeviceBaseActivity) mContext).setiNeedUpdateCount(1);

		Boolean isRuning = mRunMap.get(id);
		List<CurtainAsyncTask> taskList = mCache.get(id);

		if (isRuning == null) {
			isRuning = false;
			mRunMap.put(id, isRuning);
		}

		if (taskList == null) {
			taskList = new ArrayList<CurtainAsyncTask>();
			mCache.put(id, taskList);
		}

		if (taskList.isEmpty() && !isRuning) {
			task.execute();
			TLog.d("LightAsyncTask execute");
		} else {
			taskList.add(task);
			mCache.put(id, taskList);
			TLog.d("mCache count :" + taskList.size());
		}

	}

}
